package com.offcn.sellergoods.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.offcn.sellergoods.dao.*;
import com.offcn.sellergoods.entity.GoodsEntity;
import com.offcn.sellergoods.pojo.Goods;
import com.offcn.sellergoods.pojo.GoodsDesc;
import com.offcn.sellergoods.pojo.Item;
import com.offcn.sellergoods.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Transactional
@Service
public class GoodsServiceImpl implements GoodsService {

    @Autowired(required = false)
    private GoodsMapper goodsMapper;

    @Autowired(required = false)
    private GoodsDescMapper goodsDescMapper;

    @Autowired(required = false)
    private ItemMapper itemMapper;

    @Autowired(required = false)
    private BrandMapper brandMapper;

    @Autowired(required = false)
    private SellerMapper sellerMapper;

    @Autowired(required = false)
    private ItemCatMapper itemCatMapper;

    @Override
    public void add(GoodsEntity goodsEntity) {
        // 1. tbGoods 数据的插入
        Goods tbGoods = goodsEntity.getTbGoods();
        // 将商品的状态 修改 0
        tbGoods.setAuditStatus("0"); // 未审核通过
        goodsMapper.insert(tbGoods);
        // 1.1 获取刚刚插入 tbGoods 数据的Id
        Long goodsId = tbGoods.getId();
        // 2.tbGoodsDesc 数据的插入
        GoodsDesc tbGoodsDesc = goodsEntity.getTbGoodsDesc();
        tbGoodsDesc.setGoodsId(goodsId);
        goodsDescMapper.insert(tbGoodsDesc);
        // 3. item数据的插入
        // 判断 启用规格是否被选中
        if ("1".equals(tbGoods.getIsEnableSpec())) {  // 已经启用
            List<Item> itemList = goodsEntity.getItemList();
            if (!CollectionUtils.isEmpty(itemList)) {
                for (Item item : itemList) {
                    String goodsName = tbGoods.getGoodsName();
                    Map<String,String> specMap = JSON.parseObject(item.getSpec(), Map.class);
                    for (String key : specMap.keySet()) {
                        goodsName += " " + specMap.get(key);
                    }
                    // 非空字段
                    item.setTitle(goodsName);
                    // 非空字段
                    // 前端提交的数据  价格 price 和 库存 num，状态 status，是否默认 is_default, 规格 spec
                    // 非空字段
                    // 时间
                    item.setUpdateTime(new Date());
                    item.setCreateTime(new Date());

                    // 非空字段 商品的第三级分类的ID
                    item.setCategoryId(tbGoods.getCategory3Id());

                    // 商品ID
                    item.setGoodsId(goodsId);
                    // seller_id
                    item.setSellerId(tbGoods.getSellerId());

                    // 无法直接获取的字段
                    // brand  品牌名  ==> tbGoods中有 brandId
                    String brandName = brandMapper.selectById(tbGoods.getBrandId()).getName();
                    item.setBrand(brandName);
                    // seller 商家名  ==>  sellerId
                    String sellerName = sellerMapper.selectById(tbGoods.getSellerId()).getName();
                    item.setSeller(sellerName);
                    // category 第三级分类名 ==>  categoryId 第三级分类
                    String categoryName = itemCatMapper.selectById(tbGoods.getCategory3Id()).getName();
                    item.setCategory(categoryName);
                    // 插入数据
                    itemMapper.insert(item);
                }
            }
        }else{ // 没有启用
            Item item = new Item();
            item.setTitle(tbGoods.getGoodsName());
            item.setPrice(tbGoods.getPrice());
            item.setNum(1000); // 默认值
            item.setCategoryId(tbGoods.getCategory3Id());
            item.setStatus("0"); // 默认值
            item.setUpdateTime(new Date());
            item.setCreateTime(new Date());

            // 商品ID
            item.setGoodsId(goodsId);
            // seller_id
            item.setSellerId(tbGoods.getSellerId());

            // 无法直接获取的字段
            // brand  品牌名  ==> tbGoods中有 brandId
            String brandName = brandMapper.selectById(tbGoods.getBrandId()).getName();
            item.setBrand(brandName);
            // seller 商家名  ==>  sellerId
            String sellerName = sellerMapper.selectById(tbGoods.getSellerId()).getName();
            item.setSeller(sellerName);
            // category 第三级分类名 ==>  categoryId 第三级分类
            String categoryName = itemCatMapper.selectById(tbGoods.getCategory3Id()).getName();
            item.setCategory(categoryName);
            // 插入数据
            itemMapper.insert(item);
        }
    }

    @Override
    public GoodsEntity findById(Long goodsId) {
        // 1.查询tbGoods表
        Goods tbGoods = goodsMapper.selectById(goodsId);
        // 当前商品被删除
        if (tbGoods.getIsDelete() != null && tbGoods.getIsDelete().equals("1")){
            throw new RuntimeException("当前商品被删除");
//            return new GoodsEntity(null,null,null);
        }
        // 2.查询tbGoodsDesc表
        GoodsDesc tbGoodsDesc = goodsDescMapper.selectById(goodsId);
        // 3.查询 item表
        QueryWrapper<Item> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("goods_id",goodsId);
        List<Item> itemList = itemMapper.selectList(queryWrapper);
        return new GoodsEntity(tbGoods,tbGoodsDesc,itemList);
    }

    @Override
    public void audit(Long goodsId) {
        // 根据goodsId查询商品
        Goods tbGoods = goodsMapper.selectById(goodsId);
        // 判断商品是否已经被删除
        if (tbGoods.getIsDelete() != null && tbGoods.getIsDelete().equals("1")) {
            throw new RuntimeException("当前商品已经为删除");
        }
        // 修改商品状态
        tbGoods.setAuditStatus("1"); // 审核通过
        tbGoods.setIsMarketable("1"); // 商品自动上架
        // 持久化到数据库
        goodsMapper.updateById(tbGoods);
    }

    /**
     * 商品下架
     * @param goodsId
     */
    @Override
    public void pull(Long goodsId) {
        Goods tbGoods = goodsMapper.selectById(goodsId);
        if(tbGoods.getIsDelete() != null && tbGoods.getIsDelete().equals("1")){
            throw new RuntimeException("当前商品已被删除");
        }
        tbGoods.setIsMarketable("0"); // 商品下架
        // 持久化到数据库
        goodsMapper.updateById(tbGoods);
    }

    /**
     * 商品上架
     * @param goodsId
     */
    @Override
    public void put(Long goodsId) {
        Goods tbGoods = goodsMapper.selectById(goodsId);
        if(tbGoods.getIsDelete() != null && tbGoods.getIsDelete().equals("1")){
            throw new RuntimeException("当前商品已被删除");
        }
        tbGoods.setIsMarketable("1"); // 商品上架
        // 持久化到数据库
        goodsMapper.updateById(tbGoods);

    }

    @Override
    public void putMany(Long[] goodsIds) {
        Goods goods = new Goods();
        goods.setIsMarketable("1"); // 上架

        QueryWrapper<Goods> queryWrapper = new QueryWrapper<>();
        // 商品没有被删除
        queryWrapper.isNull("is_delete"); // 当前字段为空
        // 商品被审核通过之后 才可以上架
        queryWrapper.eq("audit_status","1");
        // 商品ID 在 goodsIds 中
        queryWrapper.in("id",goodsIds);
        // 持久化到数据库
        goodsMapper.update(goods,queryWrapper);
    }

    @Override
    public void delete(Long id) {
        Goods tbGoods = goodsMapper.selectById(id);
        // 修改状态
        tbGoods.setIsDelete("1");
        // 持久化到数据库
        goodsMapper.updateById(tbGoods);
    }
}
